package com.hxh.component.business.app;

import android.app.Application;
import android.content.Context;
import android.graphics.Color;
import android.os.Environment;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;

import com.alibaba.android.arouter.launcher.ARouter;
import com.facebook.stetho.Stetho;
import com.hxh.component.basicore.Base.app.AppManager;
import com.hxh.component.basicore.Base.app.BugManager;
import com.hxh.component.basicore.Base.app.provider.UIProvider;
import com.hxh.component.basicore.Base.topbar.ActionBarProvider;
import com.hxh.component.basicore.CoreLib;
import com.hxh.component.basicore.component.net.ConverterFactory;
import com.hxh.component.basicore.component.net.HttpInterceptor;
import com.hxh.component.basicore.component.net.NetProvider;
import com.hxh.component.basicore.component.net.RequestCodeInterceptor;
import com.hxh.component.basicore.ui.stateview.StateView;
import com.hxh.component.basicore.util.Utils;
import com.hxh.component.basicore.util.aspj.util.AspjManager;
import com.hxh.component.basicore.util.statistics.IStatistics;
import com.hxh.component.business.BuildConfig;
import com.hxh.component.business.R;
import com.hxh.component.business.common.UserInfoDTO;
import com.hxh.component.business.common.greendao.DaoMaster;
import com.hxh.component.business.common.greendao.DaoSession;
import com.hxh.component.business.utils.Constant;
import com.hxh.component.business.utils.oss.api.OSSUtil;
import com.hxh.component.business.utils.oss.request.Request_GetOssInfo;
import com.tencent.bugly.crashreport.CrashReport;
import com.tencent.smtt.sdk.QbSdk;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by hxh on 2017/7/8.
 * 此类负责app的相关组件初始化工作
 */
public class AppInitDelegate extends com.hxh.component.basicore.Base.app.AppInitDelegate {

    private static int VIEW_NODATA = 10001;
    private static int VIEW_ERROR404 = 10002;
    private static int VIEW_OTHERERROR = 10003;
    private static int VIEW_NETERROR = 10004;
    private static int VIEW_NETBAD = 10005;

    public AppInitDelegate(Application app) {
        super(app);
    }

    private String mDatasDir;
    private String mImagesDir;
    private boolean ossIsInitd = false;
    private UserInfoDTO mUserDTO;
    private DaoSession mDaoSession;
    private BugManager mBugManager;
    private HashMap<String, String> mSaveData; //SaveData可以看做一个小型数据存储库

    public void init() {
        //Looper.myLooper() != Looper.getMainLooper()

        // Utils.init(mApplication);
        mSaveData = new HashMap<>(1);
        getAppCacheDir();
        getAppImgCacheDir();
        initGreenDao();
        mUserDTO = new UserInfoDTO(mDaoSession);
        if (mUserDTO.getUser() != null) {
            initOss(); //不用初始化OSs
        } else {
            mUserDTO.setUser(null);
        }
        initBugManager();
//        initX5();
        initArouter();
        initSharpe();
        initAspj();
        initActionBarProvider();
    }

    @Override
    public void A_initCoreLib() {
        HttpInterceptor httpInterceptor = new HttpInterceptor();
        new CoreLib
                .Builder()
                .setContext(mApplication)
                .setNetProvider(
                        new NetProvider.Builder()
                                .configTokenInterceptor(httpInterceptor.buildTokenInterceptor
                                        ("Authorization", new HttpInterceptor.TokenCallBack() {
                                            @Override
                                            public String getToken() {
                                                return getUserDTO().getmCurrentToken();
                                            }
                                        }))
                                .configLogInteceptor(httpInterceptor.buildLogInterceptor())
                                .configCodeInteceptor(new RequestCodeInterceptor())
                                .configEnableConnectTimeOutRetry(false)
                                .configReadTimeOut(120)
                                .configConnectTimeOut(30)
                                .configConverterFactory(ConverterFactory.getConverter
                                        (ConverterFactory.FASTJSON))
                                .enableCache(10 * 1024 * 1024)
                                .configHttpBaseUrl(BuildConfig.AUTH_ENDPOINT)
                                .build()
                )
                .setAppStatisticsProvier(new IStatistics() {
                    @Override
                    public void openStatistics(Map<String, String> map) {

                    }

                    @Override
                    public void onAccountStatistics(String s) {

                    }

                    @Override
                    public void onAccountStatistics(String s, String s1) {

                    }

                    @Override
                    public void onCloseAccountStatistics() {

                    }

                    @Override
                    public void onFragmentPageStatistics(String s) {

                    }

                    @Override
                    public void onFragmentStatisticsEnd(String s) {

                    }

                    @Override
                    public void onActivityPageStatistics(FragmentActivity fragmentActivity) {

                    }

                    @Override
                    public void onActivityStatisticsEnd(FragmentActivity fragmentActivity) {

                    }

                    @Override
                    public void onEventStatistics(String s, Map<String, String> map) {

                    }

                    @Override
                    public void onEventStatistics(String s, Map<String, String> map, int i) {

                    }

                    @Override
                    public void onStartAppStatistics(Context context) {

                    }

                    @Override
                    public void onExitAppStatistics(Context context) {

                    }
                })
                .setUIProvider(new UIProvider.Builder()
                        .configLoadingDialogUI(R.layout.loading_dialog_view)
                        .configStateView(new StateView.Builder(mApplication)
                                .addState(VIEW_NODATA, R.layout.layout_nodata)
                                .addState(VIEW_ERROR404, R.layout.layout_error404)
                                .addState(VIEW_OTHERERROR, R.layout.layout_othererror)
                                .addState(VIEW_NETERROR, R.layout.layout_neterror)
                                .addState(VIEW_NETBAD, R.layout.layout_netbad)
                                .build())
                        .build())
                .build();
    }

    private void initGreenDao() {
        // Application 中执行
        // DevOpenHelper 每次数据库升级会清空数据，一般用于开发
        DaoMaster.DevOpenHelper devOpenHelper = new DaoMaster.DevOpenHelper(App.getContext(),
                "myworkat.db", null);
        DaoMaster daoMaster = new DaoMaster(devOpenHelper.getWritableDb());
        mDaoSession = daoMaster.newSession();

    }

    //region FileCache
    public String getAppCacheDir() {
        if (null == mDatasDir) {
            mDatasDir = Environment.getExternalStorageDirectory().getAbsolutePath() + File
                    .separator + "xakj" + File.separator;
            File file = new File(mDatasDir);
            if (!file.exists()) {
                file.mkdirs();
            }
        }
        return mDatasDir;
    }

    public String getAppImgCacheDir() {
        if (null == mImagesDir) {
            mImagesDir = getAppCacheDir() + "img";
            File file = new File(mImagesDir);
            if (!file.exists()) {
                file.mkdirs();
            }

        }
        return mImagesDir;
    }
    //endregion

    public BugManager getBugManager() {
        return mBugManager;
    }

    public UserInfoDTO getUserDTO() {

        return null == mUserDTO ? mUserDTO = new UserInfoDTO(mDaoSession) : mUserDTO;
    }

    //region init方法

    private void initStetho() {
        Stetho.initializeWithDefaults(mApplication);
    }

    /**
     * 请使用 OssUtil里面的初始化方法
     */
    public void initOss() {
        //以下是示例，可以自行更改
        if (!ossIsInitd || null == OSSUtil.mDefaultinitOSSResponse) {
            ossIsInitd = true;
            OSSUtil
                    .initOss_default(new Request_GetOssInfo(Constant.OSSId.OSS_CONTRACT, "sdk",
                            ""));
        }
    }

    private void initBugManager() {
        mBugManager = new BugManager() {
            @Override
            public void postBug(Exception e) {
                CrashReport.postCatchedException(e);
            }

            @Override
            public void postBug(Throwable e) {
                CrashReport.postCatchedException(e);
            }

            @Override
            public void init() {
                // 获取当前包名
                String packageName = mApplication.getPackageName();
                // 获取当前进程名
                String processName = AppManager.getProcessName(android.os.Process.myPid());
                // 设置是否为上报进程
                CrashReport.UserStrategy strategy = new CrashReport.UserStrategy(mApplication);
                strategy.setUploadProcess(processName == null || processName.equals(packageName));
                CrashReport.initCrashReport(mApplication, "d8a71ed226", false);
            }
        };
        mBugManager.init();
        CoreLib.getInstance().getAppComponent().globalBugManager(mBugManager);

    }


    private void initX5() {
        QbSdk.setDownloadWithoutWifi(true);//非wifi条件下允许下载X5内核
        QbSdk.PreInitCallback cb = new QbSdk.PreInitCallback() {

            @Override
            public void onViewInitFinished(boolean arg0) {
                //x5內核初始化完成的回调，为true表示x5内核加载成功，否则表示x5内核加载失败，会自动切换到系统内核。
            }

            @Override
            public void onCoreInitFinished() {
            }
        };
        QbSdk.initX5Environment(mApplication, cb);
    }

    /**
     * 初始化Arouter
     */
    private void initArouter() {
        if (BuildConfig.DEBUG) {
            ARouter.openLog();     // 打印日志
            ARouter.openDebug();   // 开启调试模式(如果在InstantRun模式下运行，必须开启调试模式！线上版本需要关闭,否则有安全风险)
            //
        }
        ARouter.init(mApplication);
    }

    private void initActionBarProvider() {
        CoreLib.getInstance().getAppComponent().globalUIProvider().setActionBarProvider(new
                ActionBarProvider.Builder()
                .background(Color.parseColor("#ffffff"))
                .enableImmeriveMode()
                .backImg(Utils.BitmapUtils.getBitmap(R.drawable.arrow_back_black))
                .build());
    }

    private void initAspj() {
        AspjManager.CheckLoginManager.getInstance().registerLoginView(Constant
                .RouterPath_DefalutLoginView, AspjManager.CheckLoginManager.MODE_ACTIVTY);
    }

    public DaoSession getDaoSession() {
        return mDaoSession;
    }

    //endregion

    public void saveData(String key, String value) {
        if (mSaveData.containsKey(key)) mSaveData.remove(key);
        mSaveData.put(key, value);
    }

    public String getData(String key) {
        return TextUtils.isEmpty(mSaveData.get(key)) ? "" : mSaveData.get(key);
    }

    public String getAPKSavePath() {
        return getAppCacheDir() + Constant.APPUPDATEFILENAME;
    }
}
